﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Demo.Models;
using Demo.Repository;
using Demo.Request;
using Demo.Db;

namespace Demo.Controllers
{
    public class HomeController : Controller
    {
        private readonly EfRepository<ProductInfo> _ef;

        public HomeController()
        {
            _ef = new EfRepository<ProductInfo>();
        }

        public IActionResult Index()
        {
            var db = new DemoDb();
            var ef = new EfRepository<CategoryInfo>();
            var sql = from Id in _ef.table select Id;
            return View(sql);
        }
        public IActionResult Add(int id)
        {
            var entity = _ef.GetById(id);
            return View(entity);
        }
        [HttpPost]
        public IActionResult Save(ProductRequest request)
        {
            var entity = _ef.GetById(request.Id);
            if (request.Id > 0)
            {
                entity.ProductName = request.ProductName;
                entity.Supplier = request.Supplier;
                entity.Price = request.Price;
                entity.Stock = request.Stock;
                entity.Remarks = request.Remarks;
                _ef.Update(entity);
            }
            else
            {
                _ef.Insert(new ProductInfo
                {
                    ProductName = request.ProductName,
                    Supplier = request.Supplier,
                    Price = request.Price,
                    Stock = request.Stock,
                    Remarks = request.Remarks,
                    UpdatedTime = DateTime.Now
                });
            }
            return Ok();
        }
        public IActionResult Delete(int id)
        {
            _ef.Delete(id);
            return RedirectToAction("Index");
        }

        // 按商品名称和备注搜索
        public IActionResult Select(SelectRequest request)
        {
            var entity = _ef.table.Where(x => x.IsDeleted == false).ToList();
            if (request.Text != null || request != null || request.Text.Length > 0)
            {
                entity = _ef.table.Where(x => x.IsDeleted == false && x.ProductName.Contains(request.Text) || x.Remarks.Contains(request.Text)).ToList();
            }
            return Json(entity);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
